package com.ihai.spring.boot.sample.rabbitmq;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * DESC
 *
 * @author 张驰
 * @date 2018/3/2
 */
public class Provider {
    private final static Logger logger = LoggerFactory.getLogger(Provider.class);
    private final RabbitTemplate rabbitTemplate;

    public Provider(RabbitTemplate rabbitTemplate, String exchangeName, String qName) {
        this.rabbitTemplate = rabbitTemplate;
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("provider-pool-%d").build();
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1, threadFactory);
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                logger.info("Sending message...");
                //直接向队列发送消息
                rabbitTemplate.convertAndSend(qName, "Send to " + qName);
                rabbitTemplate.convertAndSend(exchangeName, qName, "Send to " + exchangeName);
            }
        }, 1000, 1000, TimeUnit.MILLISECONDS);
    }

}
